package com.cndw.kungfu.business;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;

import com.cndw.kungfu.comm.GmCommand;
import com.cndw.kungfu.comm.LocalCommand;
import com.cndw.kungfu.config.ConstantsConfig;
import com.cndw.kungfu.config.ConstantsCore;
import com.cndw.kungfu.config.ConstantsCost;
import com.cndw.kungfu.config.ConstantsIntKey;
import com.cndw.kungfu.config.ConstantsLog;
import com.cndw.kungfu.config.ConstantsRadio;
import com.cndw.kungfu.config.ConstantsSystem;
import com.cndw.kungfu.domain.GoodsMode;
import com.cndw.kungfu.domain.Player;
import com.cndw.kungfu.event.once.PlayerPayTask;
import com.cndw.kungfu.ext.LanguageLib;
import com.cndw.kungfu.ext.LogUtil;
import com.cndw.kungfu.ext.MD5;
import com.cndw.kungfu.model.Context;
import com.cndw.kungfu.model.business.IPayManager;
import com.cndw.kungfu.model.business.domain.PayGoods;
import com.cndw.kungfu.model.goods.domain.SubPops;
import com.cndw.kungfu.model.sys.LogServer;
import com.cndw.kungfu.vo.EventNotice;
import com.cndw.kungfu.vo.PlayerChangeVO;
import com.cndw.rpg.annotation.Controller;
import com.cndw.rpg.annotation.UnAuth;
import com.cndw.rpg.framework.ResponseMessage;
import com.cndw.rpg.framework.Session;

/**
 * 充值接口
 * 
 * @author fantadust [9677889@qq.com]
 * @date 2011-6-8 上午11:14:54
 */
@Controller
public class BusinessPay {

	@Autowired
	private IPayManager iPayManager;

	@UnAuth
	@GmCommand
	public ResponseMessage qqpay(Session session, String gmSign, Map<String, String> payMap) {
		String[] params = new String[] { "openid", "payitem", "billno", "providetype", "amt", "payamtCoins", "serverId", "sign" };
		for (String e : params) {
			if (!payMap.containsKey(e)) {
				return ResponseMessage.getFailMessage(-1001);
			}
		}
		if (ConstantsSystem.getCloseState() > 0) {
			return ResponseMessage.getFailMessage(-444);
		}
		StringBuilder sb = new StringBuilder();
		sb.append("openid=").append(payMap.get("openid").toString());
		sb.append("&payitem=").append(payMap.get("payitem").toString());
		sb.append("&billno=").append(payMap.get("billno").toString());
		sb.append("&providetype=").append(payMap.get("providetype").toString());
		sb.append("&amt=").append(payMap.get("amt").toString());
		sb.append("&payamtCoins=").append(payMap.get("payamtCoins").toString());
		sb.append("&serverId=").append(payMap.get("serverId").toString());
		sb.append("&key=").append(ConstantsConfig.getSysCgKeyPay());

		if (!MD5.compile(sb.toString()).equals(payMap.get("sign").toString())) {
			return ResponseMessage.getFailMessage(-1002);
		}

		if (!payMap.get("serverId").toString().equals(ConstantsConfig.getSysCgSvrId())) {

		}
		String accountName = null, transactionId = null, payitem = null;
		int addcoin = 0, exchangeType = 0;
		float money = 0, depay = 0, gDepay = 0;
		try {
			accountName = payMap.get("openid").trim();
			transactionId = payMap.get("billno").trim();
			payitem = payMap.get("payitem").trim();
			money = Float.parseFloat(payMap.get("amt").trim()) / 100;
			if (payMap.get("payamtCoins").trim() != null && payMap.get("payamtCoins").trim().length() > 0) {
				depay = Float.parseFloat(payMap.get("payamtCoins").trim().toString());
			}
			if (payMap.containsKey("payamtGame") && payMap.get("payamtGame").trim() != null && payMap.get("payamtGame").trim().length() > 0) {
				gDepay = Float.parseFloat(payMap.get("payamtGame").trim().toString());
			}

			addcoin = Integer.valueOf(payMap.get("providetype").trim().toString());

		} catch (Exception e) {
			e.printStackTrace();
			return ResponseMessage.getFailMessage(-1003);
		}

		long playerId = Context.getPlayerServer().getPlayerIdByAccount(accountName);
		if (playerId == 0) {
			return ResponseMessage.getFailMessage(-1008);
		}
		Player player = Context.getPlayerServer().getByPlayerId(playerId);
		if (player == null) {
			return ResponseMessage.getFailMessage(-1008);
		}

		if (iPayManager.selectOrderId(transactionId, accountName) > 0) {
			LogUtil.getMain().debug("no is have : accountName:" + accountName + " | " + transactionId);
			return ResponseMessage.getSuccMessage(1);
		}
		int gold = 0;
		int liquan = 0;
		int payTypeId = 0;
		try {
			String[] mes = payitem.split("\\*");
			payTypeId = Integer.valueOf(mes[0].toString());
			int num = Integer.valueOf(mes[2].toString());

			PayGoods payGoods = PayGoods.getPayGoods(payTypeId);
			liquan = payGoods.getLiquan() * num;
			gold = payTypeId * num;// 暂时
		} catch (Exception e) {
			LogUtil.getMain().debug(payitem);
		}
		int goldAll = gold + liquan;

		int id = Context.getBusinessServer().payInsertDB(player, transactionId, addcoin, money, gold, exchangeType, depay, gDepay, goldAll);

		if (id == 0) {
			LogUtil.getMain().debug("err db: accountName:" + accountName + " | " + transactionId);
			return ResponseMessage.getFailMessage(-1009);
		}
		boolean mailSend = false;
		int awardId = 0;
		if (payTypeId == 5000) {
			try {
				awardId = 102101;
				// if (player.getDataInfo().intDataGet(ConstantsIntKey.pg) == 0)
				// {
				// awardId = 189011;
				// player.getDataInfo().intDataSet(ConstantsIntKey.pg, 1);
				// }//首充特别活动
				if (player.getPlayerBoxs().checkBlack()) {
					Context.getGoodsServer().giveGoodsBing(playerId, awardId, 1, 1);
				} else {
					mailSend = true;
					GoodsMode goodsMode = Context.getGoodsServer().getModeById(awardId);

					String title = LanguageLib.get("pay.money.title");
					String content = LanguageLib.get("pay.moeny.message", goodsMode.getName());
					List<SubPops> attachment = new ArrayList<SubPops>();
					attachment.add(new SubPops(awardId, 1, 0, 0));
					Context.getMessageServer().sendSysMail(playerId, player.getPlayerName(), title, content, attachment);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		player.receiveGold(goldAll);
		PlayerPayTask command = new PlayerPayTask(player, (int) (money * 100));
		Context.getTimerServer().execute(command);
		player.commitSync();
		player.getDataInfo().intDataSet(ConstantsIntKey.payTrue, 1);
		player.getDataInfo().commitSync();
		LogServer.recordLog(player, ConstantsLog.gold, 50001, money, goldAll, exchangeType, transactionId, awardId, mailSend);

		return ResponseMessage.getSuccMessage(1);
	}

	@UnAuth
	@GmCommand
	public ResponseMessage qqActivity(Session session, String gmSign, Map<String, String> dataMap) {
		if (ConstantsSystem.getCloseState() > 0) {
			return ResponseMessage.getFailMessage(-444);
		}
		String openid = dataMap.get("openid").trim();
		String payitem = dataMap.get("payitem").trim();
		String billno = dataMap.get("billno").trim();
		String providetype = dataMap.get("providetype").trim();
		String discountid = dataMap.get("discountid").trim();
		String serverId = dataMap.get("serverId").trim();
		String sign = dataMap.get("sign").trim();

		StringBuilder sb = new StringBuilder();
		sb.append("openid=").append(openid);
		sb.append("&payitem=").append(payitem);
		sb.append("&billno=").append(billno);
		sb.append("&providetype=").append(providetype);
		sb.append("&discountid=").append(discountid);
		sb.append("&serverId=").append(serverId);
		sb.append("&key=").append(ConstantsConfig.getSysCgKeyPay());

		if (!MD5.compile(sb.toString()).equals(sign)) {
			LogUtil.getMain().error(" err " + sb.toString());
			return ResponseMessage.getFailMessage(-1002);
		}
		if (!serverId.equals(ConstantsConfig.getSysCgSvrId())) {
			LogUtil.getMain().error(" sid " + serverId);
		}
		long playerId = Context.getPlayerServer().getPlayerIdByAccount(openid);
		if (playerId == 0) {
			return ResponseMessage.getFailMessage(-1008);
		}
		Player player = Context.getPlayerServer().getByPlayerId(playerId);
		if (player == null) {
			return ResponseMessage.getFailMessage(-1008);
		}

		String[] mes = payitem.split("\\*");
		int actGoodsId = Integer.valueOf(mes[0].toString());
		int actNum = Integer.valueOf(mes[2].toString());

		boolean got = player.getDataInfo().intDataGet(ConstantsIntKey.yelAct) != ConstantsCore.yelGotSign;
		boolean mailSend = false;
		String awardName = null;
		if (got) {
			actGoodsId = 103613;
			actNum = 1;
			GoodsMode goodsMode = Context.getGoodsServer().getModeById(actGoodsId);
			if (goodsMode != null) {
				awardName = goodsMode.getName();
			}	else {
				LogUtil.getMain().error("err awardid ");
			}
			if (player.getPlayerBoxs().checkBlack()) {
				Context.getGoodsServer().giveGoodsBing(playerId, actGoodsId, actNum, 1);
			} else {
				mailSend = true;
				String title = LanguageLib.get("pay.yellow.title");
				String content = LanguageLib.get("pay.yellow.message");
				List<SubPops> attachment = new ArrayList<SubPops>();
				attachment.add(new SubPops(actGoodsId, actNum, 0, 0));
				Context.getMessageServer().sendSysMail(playerId, player.getPlayerName(), title, content, attachment);
			}
			player.receiveGold(100);
			LogServer.gotEventLog(player.getPlayerId(), 100, ConstantsCost.gotPayYel);
			player.commitSync();
			Context.getPlayerServer().change(PlayerChangeVO.PLAYER_GOLD, player.getGold(), playerId);
		}
		player.getDataInfo().intDataSet(ConstantsIntKey.yelAct, ConstantsCore.yelGotSign);
		player.getDataInfo().commitSync();

		EventNotice notice = new EventNotice(ConstantsRadio.holiday, ConstantsRadio.holiday_yellowVip);
		notice.put("yetAct", false);
		notice.broadcast(player.getPlayerId());

		LogServer.recordLog(player, ConstantsLog.gold, 50007, got, billno, providetype, discountid, payitem, mailSend, ConstantsCore.yelGotSign,awardName);

		return ResponseMessage.getSuccMessage(1);
	}

	@UnAuth
	@GmCommand
	public ResponseMessage pay(Session session, String gmSign, Map<String, String> payMap) {
		if (ConstantsSystem.getCloseState() > 0) {
			return ResponseMessage.getFailMessage(-444);
		}
		String[] params = new String[] { "addcoin", "uname", "gameId", "serviceId", "money", "transactionId", "exchangeType", "depay", "gDepay", "sign" };
		for (String e : params) {
			if (!payMap.containsKey(e)) {
				return ResponseMessage.getFailMessage(LanguageLib.get("pay.err.missargs", e));
			}
		}
		String accountName = null, serviceId = null, transactionId = null, sign = null;
		int addcoin = 0, gameId = 0, exchangeType = 0;
		float money = 0, depay = 0, gDepay = 0;
		try {

			accountName = payMap.get("uname").trim();
			serviceId = payMap.get("serviceId").trim();
			transactionId = payMap.get("transactionId").trim();
			sign = payMap.get("sign").trim();

			addcoin = Integer.parseInt(payMap.get("addcoin"));
			gameId = Integer.parseInt(payMap.get("gameId"));
			exchangeType = Integer.parseInt(payMap.get("exchangeType"));

			money = Float.parseFloat(payMap.get("money"));
			depay = Float.parseFloat(payMap.get("depay"));
			gDepay = Float.parseFloat(payMap.get("gDepay"));

		} catch (Exception e) {
			e.printStackTrace();
			return ResponseMessage.getFailMessage(LanguageLib.get("pay.err.wrongargs"));
		}

		if (serviceId != ConstantsConfig.getSysCgSvrId()) {
			// return
			// ResponseMessage.getFailMessage(LanguageLib.get("pay.err.serverid"));
		}
		StringBuilder sb = new StringBuilder();
		sb.append("depay=").append(depay);
		sb.append("&gDepay=").append(gDepay);
		sb.append("&addcoin=").append(addcoin);
		sb.append("&uname=").append(accountName);
		sb.append("&money=").append(money);
		sb.append("&gameId=").append(gameId);
		sb.append("&serviceId=").append(serviceId);
		sb.append("&transactionId=").append(transactionId);
		sb.append("&exchangeType=").append(exchangeType);
		sb.append("&key=").append(ConstantsConfig.getSysCgKeyPay());

		if (!sign.equals(MD5.compile(sb.toString()))) {
			LogUtil.getMain().debug("err sign accountName:" + accountName);
			return ResponseMessage.getFailMessage(LanguageLib.get("pay.err.sign"));
		}

		long playerId = Context.getPlayerServer().getPlayerIdByAccount(accountName);
		if (playerId == 0) {
			return ResponseMessage.getFailMessage(LanguageLib.get("pay.err.payer"));
		}
		Player player = Context.getPlayerServer().getByPlayerId(playerId);
		if (player == null) {
			return ResponseMessage.getFailMessage(LanguageLib.get("pay.err.payer"));
		}
		float curretDepay = gDepay != 0 ? gDepay : depay;
		int sysCgPayRate = ConstantsConfig.getSysCgPayRate() == 0 ? 10 : ConstantsConfig.getSysCgPayRate();
		int gold = (int) ((money - curretDepay) * sysCgPayRate);

		if (addcoin == 1) {// 套餐

		}
		if (iPayManager.selectOrderId(transactionId, accountName) > 0) {
			LogUtil.getMain().debug("err accountName:" + accountName + " | " + transactionId);
			return ResponseMessage.getSuccMessage(1);
		}

		int id = Context.getBusinessServer().payInsertDB(player, transactionId, addcoin, money, gold, exchangeType, curretDepay, gDepay, gold);

		if (id == 0) {
			LogUtil.getMain().debug("err db: accountName:" + accountName + " | " + transactionId);
			return ResponseMessage.getFailMessage(LanguageLib.get("pay.err.db"));
		}
		// 增加暑期活动任务完成标志
		// int hTask = player.getDataInfo().intDataGet(ConstantsIntKey.hTask);
		// player.getDataInfo().intDataSet(ConstantsIntKey.hTask, hTask | 2);

		player.receiveGold(gold);
		PlayerPayTask command = new PlayerPayTask(player);
		Context.getTimerServer().execute(command);
		player.getDataInfo().intDataSet(ConstantsIntKey.payTrue, 1);
		player.commitSync();
		player.getDataInfo().commitSync();
		LogServer.recordLog(player, ConstantsLog.gold, 50001, money, gold, exchangeType, transactionId);

		return ResponseMessage.getSuccMessage(1);
	}

	@LocalCommand
	public ResponseMessage test(Session session, int cash) {
		Map<String, String> payMap = new LinkedHashMap<String, String>();

		String[] params = new String[] { "openid", "payitem", "billno", "providetype", "amt", "payamtCoins", "serverId" };
		for (String e : params) {
			payMap.put(e, String.valueOf(1));
		}
		payMap.put("openid", session.getAccountName());
		payMap.put("amt", String.valueOf(cash));
		payMap.put("payitem", cash + "*1*1");
		payMap.put("billno", UUID.randomUUID().toString());
		StringBuilder sb = new StringBuilder();
		for (String e : params) {
			sb.append(e).append("=").append(payMap.get(e)).append("&");
		}
		sb.append("key=").append(ConstantsConfig.getSysCgKeyPay());
		payMap.put("sign", MD5.compile(sb.toString()));
		
		if (cash == 10000) {
			payMap.clear();
			params = new String[] { "openid", "payitem", "billno", "providetype", "discountid", "serverId" };
			for (String e : params) {
				payMap.put(e, String.valueOf(1));
			}
			payMap.put("openid", session.getAccountName());
			payMap.put("payitem", cash + "*1*1");
			payMap.put("billno", UUID.randomUUID().toString());
			sb.delete(0, sb.length());
			for (String e : params) {
				sb.append(e).append("=").append(payMap.get(e)).append("&");
			}
			sb.append("key=").append(ConstantsConfig.getSysCgKeyPay());
			System.out.println(sb.toString());
			payMap.put("sign", MD5.compile(sb.toString()));
			qqActivity(session, "xxx", payMap);
		}else {
			qqpay(session, "xxxx", payMap);
		}

		return null;
	}
}
